package com.capgemini.expense.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

public class JPADao<E> implements GenericDAO<Long, E> {

	protected Class<E> managedEntitiesType;

	@Override
	public E get(Long id) {
		EntityManager em = EntityManagerFactoryHolder.get().createEntityManager();
		try {
			return (E) em.find(managedEntitiesType, id);
		} finally {
			em.close();
		}
	}

	@Override
	public void saveOrUpdate(E entity) {
		EntityManager em = EntityManagerFactoryHolder.get().createEntityManager();
		try {
			em.persist(entity);
			em.merge(entity);
		} finally {
			em.close();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<E> getAll() {
		int i = 0;
		EntityManager em = EntityManagerFactoryHolder.get().createEntityManager();
		try {
			Query q = em.createQuery("SELECT c from " + managedEntitiesType.getName() + " c");
			List<E> resultList = q.getResultList();
			resultList.size(); // small hack to avoid Object Manager has been
								// closed
			return resultList;
		} finally {
			em.close();
		}
	}

	@Override
	public void delete(E entity) {
		EntityManager em = EntityManagerFactoryHolder.get().createEntityManager();
		try {
			em.remove(entity);
		} finally {
			em.close();
		}
	}

}
